package eventplanner.ejb;

import java.util.Calendar;

import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This EJB (@Singleton & @Startup) schedules and executes the cleaning of the database of
 * Tokens which haven't been used in X months. The schedule is once a week.
 */
@Singleton
@Startup
public class Cleaner {

	private static final Logger LOG = LoggerFactory.getLogger(Cleaner.class);
	private static final int THRESHOLD = 1;

	@PersistenceContext
	private EntityManager em;

	/**
	 * Searches the database for unused Tokens and removes these. Scheduled to run once a week.
	 */
	@Schedule(dayOfWeek = "0")
	public void clean() {
		Query query = em.createQuery("delete from Token t where t.lastViewDate < ?1");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -1 * THRESHOLD);

		query.setParameter(1, cal.getTime());
		int rowsDeleted = query.executeUpdate();

		LOG.info("The cleaner removed {} tokens from the database which weren't used for over {} month(s)", rowsDeleted, THRESHOLD);
	}
}
